import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { Codewin } from '@/api/generated/Codewin'
// import type { UserVO } from '@/api/generated/data-contracts'
import { useAuthStore } from './auth'

export interface UserProfile {
  id: string
  username: string
  email: string
  avatar?: string
  nickname?: string
  phone?: string
  createTime?: string
  lastLoginTime?: string
  /**
   * 用户身份(0：用户 1：管理员）
   */
  identity?: number
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const profile = ref<UserProfile | null>(null)
  const preferences = ref({
    theme: 'light' as 'light' | 'dark',
    language: 'zh-CN',
    notifications: true
  })
  const loading = ref(false)

  // API实例
  const api = new Codewin({
    baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top',
  })

  // 计算属性
  const displayName = computed(() => {
    if (!profile.value) return ''
    return profile.value.nickname || profile.value.username || profile.value.email
  })

  const hasProfile = computed(() => !!profile.value)

  // 管理员状态计算属性
  const isAdmin = computed(() => {
    return profile.value?.identity === 1
  })

  const userRole = computed(() => {
    if (!profile.value) return 'unknown'
    return profile.value.identity === 1 ? 'admin' : 'user'
  })

  // 方法
  function setProfile(userProfile: UserProfile) {
    profile.value = userProfile
  }

  function updateProfile(updates: Partial<UserProfile>) {
    if (profile.value) {
      profile.value = { ...profile.value, ...updates }
    }
  }

  function setPreferences(newPreferences: Partial<typeof preferences.value>) {
    preferences.value = { ...preferences.value, ...newPreferences }
  }

  function clearProfile() {
    profile.value = null
    preferences.value = {
      theme: 'light',
      language: 'zh-CN',
      notifications: true
    }
  }

  // 获取当前用户信息
  async function fetchUserInfo() {
    const authStore = useAuthStore()
    
    if (!authStore.isLoggedIn || authStore.isTokenExpired) {
      return null
    }

    loading.value = true
    try {
      // 设置Authorization header
      api.instance.defaults.headers.common['Authorization'] = `Bearer ${authStore.token}`
      
      const response = await api.getCurrentUserInfo()
      
      if (response.data && response.data.code === 0 && response.data.data) {
        const userData = response.data.data
        const userProfile: UserProfile = {
          id: userData.id?.toString() || '',
          username: userData.username || '',
          email: userData.email || '',
          avatar: userData.avatar,
          nickname: userData.nickname,
          phone: '', // API中没有phone字段，保持为空
          createTime: '', // API中没有createTime字段，保持为空
          lastLoginTime: '', // API中没有lastLoginTime字段，保持为空
          identity: userData.identity // 添加管理员身份字段
        }
        setProfile(userProfile)
        return userProfile
      }
      return null
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    } finally {
      loading.value = false
    }
  }

  function initUser() {
    // 持久化插件会自动恢复状态，无需手动操作
    // 如果有token但没有用户信息，则尝试获取
    const authStore = useAuthStore()
    if (authStore.isLoggedIn && !profile.value) {
      fetchUserInfo()
    }
  }

  return {
    profile,
    preferences,
    loading,
    displayName,
    hasProfile,
    isAdmin,
    userRole,
    setProfile,
    updateProfile,
    setPreferences,
    clearProfile,
    fetchUserInfo,
    initUser
  }
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    pick: ['profile', 'preferences'] // 持久化用户信息和偏好设置
  }
})
